from django.core.paginator import Paginator
from django.db.models import ProtectedError
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from usermanage.models import User, UserType, CheJian, GongQu, SelectCollection


@csrf_exempt
def login(request):
    username = request.POST['username']
    password = request.POST['password']
    user = User.objects.filter(username=username, password=password)
    if len(user) > 0:
        return JsonResponse({"code": 200, 'message': '登录成功'})
    return JsonResponse({"code": 500, 'message': '登录失败'})


@csrf_exempt
def updatePassword(request):
    oldPassword = request.POST['pass1']
    newPassword = request.POST['pass2']
    admin = User.objects.get(username='admin')
    if admin.password == oldPassword:
        admin.password = newPassword
        admin.save()
    return JsonResponse({'code': 200, 'message': '成功'})


@csrf_exempt
def add(request):
    name = request.POST['name']
    phone = request.POST['phone']
    gongQuId = int(request.POST['gongQuId'])
    user = User.objects.create(name=name, phone=phone, gong_qu_id=gongQuId)
    if user.id is None:
        return JsonResponse({"code": 500, 'message': '添加失败'})
    return JsonResponse({"code": 200, 'message': '添加成功'})


@csrf_exempt
def update(request):
    id = request.POST['id']
    name = request.POST['name']
    phone = request.POST['phone']
    gongQu = request.POST['gongQu']
    User.objects.filter(id=id).update(name=name, phone=phone, gong_qu=gongQu)
    return JsonResponse({"code": 200, "message": "修改成功"})


@csrf_exempt
def delete(request):
    id = request.GET['id']
    try:
        User.objects.filter(id=id).delete()
    except ProtectedError:
        return JsonResponse({"code": 500, "message": "删除失败"})

    return JsonResponse({"code": 200, "message": "删除成功"})


@csrf_exempt
def pageUsers(request):
    limit = request.GET['limit']
    page = int(request.GET['page'])
    userList = User.objects.all()
    paginator = Paginator(userList, limit)  # 分为几页
    if paginator.num_pages < page:
        page -= 1
    if 1 > page:
        page = 1
    page = paginator.page(page)
    usersJson = []
    for item in page:
        gong = GongQu.objects.filter(id=int(item.gong_qu_id)).values(
            'id', 'name', 'che_jian__name', 'che_jian_id')[0]
        user = {'id': item.id, 'name': item.name, 'phone': item.phone
                , 'gongQu': gong['name'], 'gongQuId': gong['id']
                , 'cheJianId': gong['che_jian_id'], 'cheJian': gong['che_jian__name']}
        usersJson.append(user)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {
        'list': usersJson, 'length': len(userList)}})


# 返回无分页的用户列表
def users(request):
    id = request.GET['id']
    userList = User.objects.filter(gong_qu__id=id)
    usersJson = []
    for item in userList:
        user = {'id': item.id, 'name': item.name+"  "+item.phone}
        usersJson.append(user)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': usersJson}})


# 添加UserType
@csrf_exempt
def addType(request):
    # 1 负责人  2 联络员  3 防护员
    type = request.GET["type"]
    id = request.GET["id"]
    userType = UserType.objects.filter(user_id=id, type=type)
    if len(userType) > 0:
        return JsonResponse({"code": 500, 'message': '该人员已存在'})
    userType = UserType.objects.create(user_id=id, type=type)
    userType.save()
    if userType.id is None:
        return JsonResponse({"code": 500, 'message': '添加失败'})
    return JsonResponse({"code": 200, 'message': '添加成功'})


# 删除UserType
@csrf_exempt
def deleteType(request):
    id = request.GET['id']
    try:
        UserType.objects.filter(id=id).delete()
    except ProtectedError:
        return JsonResponse({"code": 500, "message": "删除失败"})

    return JsonResponse({"code": 200, "message": "删除成功"})


# 返回有分页的UserType的列表
def listTypePage(request):
    limit = request.GET['limit']
    page = int(request.GET['page'])
    type = request.GET['type']
    userList = User.objects.filter(usertype__type=type)
    paginator = Paginator(userList, limit)  # 分为几页
    if paginator.num_pages < page:
        page -= 1
    if 1 > page:
        page = 1
    page = paginator.page(page)
    usersJson = []
    for item in page:
        gong = GongQu.objects.filter(id=int(item.gong_qu_id)).values(
            'id', 'name', 'che_jian__name', 'che_jian_id')[0]
        userType = UserType.objects.filter(user_id=item.id, type=type).first()
        print(userType)
        user = {'id': userType.id, 'name': item.name, 'phone': item.phone
            , 'gongQu': gong['name'], 'gongQuId': gong['id']
            , 'cheJianId': gong['che_jian_id'], 'cheJian': gong['che_jian__name']}
        usersJson.append(user)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {
        'list': usersJson, 'length': len(userList)}})


# 返回UserType的下拉框列表
def listType(request):
    type = request.GET['type']
    userList = User.objects.filter(usertype__type=type)
    usersJson = []
    for item in userList:
        user = {'id': item.id, 'name': item.name, 'phone': item.phone}
        usersJson.append(user)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': usersJson}})


# 分页车间数据显示
def pageChe(request):
    cheList = CheJian.objects.all()
    limit = request.GET['limit']
    page = int(request.GET['page'])
    paginator = Paginator(cheList, limit)  # 分为几页
    if paginator.num_pages < page:
        page -= 1
    if 1 > page:
        page = 1
    page = paginator.page(page)
    cheJson = []
    for item in page:
        cheJian = {'id': item.id, 'name': item.name, "phone": item.phone}
        cheJson.append(cheJian)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': cheJson, 'length': len(cheList)}})


# 下拉框的车间数据
def listChe(request):
    cheList = CheJian.objects.all()
    cheJson = []
    for item in cheList:
        cheJian = {'id': item.id, 'name': item.name, "phone": item.phone}
        cheJson.append(cheJian)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': cheJson}})


# 删除车间 TODO：未处理级联删除问题
@csrf_exempt
def deleteChe(request):
    id = request.GET['id']
    try:
        CheJian.objects.filter(id=id).delete()
    except ProtectedError:
        return JsonResponse({"code": 500, "message": "删除失败"})

    return JsonResponse({"code": 200, "message": "删除成功"})


# 更新车间数据
@csrf_exempt
def updateChe(request):
    name = request.POST['name']
    phone = request.POST['phone']
    id = request.POST['id']
    CheJian.objects.filter(id=id).update(name=name, phone=phone)
    return JsonResponse({"code": 200, "message": "修改成功"})


# 添加车间
@csrf_exempt
def addChe(request):
    name = request.POST['name']
    phone = request.POST['phone']
    cheJian = CheJian.objects.create(name=name, phone=phone)
    cheJian.save()
    if cheJian.id is None:
        return JsonResponse({"code": 500, 'message': '添加失败'})
    return JsonResponse({"code": 200, 'message': '添加成功'})


# 添加工区数据
@csrf_exempt
def addGong(request):
    name = request.POST['name']
    phone = request.POST['phone']
    cheJianId = request.POST['cheJianId']
    gongqu = GongQu.objects.create(name=name, phone=phone, che_jian_id=cheJianId)
    if gongqu.id is None:
        return JsonResponse({"code": 500, 'message': '添加失败'})
    return JsonResponse({"code": 200, 'message': '添加成功'})


# 更新工区数据
@csrf_exempt
def updateGong(request):
    id = request.POST['id']
    name = request.POST['name']
    phone = request.POST['phone']
    cheJianId = int(request.POST['cheJianId'])
    GongQu.objects.filter(id=id).update(name=name, phone=phone, che_jian_id=cheJianId)
    return JsonResponse({"code": 200, 'message': '修改成功'})


# 删除工具 TODO:未处理级联删除可能出现的异常
@csrf_exempt
def deleteGong(request):
    id = request.POST['id']

    try:
        GongQu.objects.filter(id=id).delete()
    except ProtectedError:
        return JsonResponse({"code": 500, "message": "删除失败"})

    return JsonResponse({"code": 200, "message": "删除成功"})


# 工区下拉框获取
def listGong(request):
    cheJianId = request.GET['cheJianId']
    gongList = GongQu.objects.all().filter(che_jian_id=cheJianId)
    gongJson = []
    for item in gongList:
        gongQu = {'id': item.id, 'name': item.name+"  "+item.phone}
        gongJson.append(gongQu)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': gongJson}})


# 工区分页数据
def pageGong(request):
    gongList = GongQu.objects.all().values('id', 'name', 'phone', 'che_jian__name', 'che_jian_id')
    limit = request.GET['limit']
    page = int(request.GET['page'])
    paginator = Paginator(gongList, limit)  # 分为几页
    if paginator.num_pages < page:
        page -= 1
    if 1 > page:
        page = 1
    page = paginator.page(page)
    gongJson = []
    for item in page:
        gongQu = {'id': item["id"], 'name': item["name"], "cheJian": item['che_jian__name'],
                  'cheJianId': item['che_jian_id'], "phone": item['phone']}
        gongJson.append(gongQu)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': gongJson, 'length': len(gongList)}})


def listSelectPage(request):
    limit = request.GET['limit']
    page = int(request.GET['page'])
    type = request.GET['type']
    selectList = SelectCollection.objects.filter(type=type)
    paginator = Paginator(selectList, limit)
    if paginator.num_pages < page:
        page -= 1
    if 1 > page:
        page = 1
    page = paginator.page(page)
    selectJson = []
    for item in page:
        select = {'id': item.id, 'name': item.name}
        selectJson.append(select)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': selectJson, 'length': len(selectList)}})


def listSelect(request):
    type = request.GET['type']
    selectList = SelectCollection.objects.filter(type=type)
    selectJson = []
    for item in selectList:
        select = {'id': item.id, 'name': item.name}
        selectJson.append(select)
    return JsonResponse({"code": 200, "message": "查询成功", "data": {'list': selectJson}})


@csrf_exempt
def deleteSelect(request):
    id = request.GET['id']
    try:
        SelectCollection.objects.filter(id=id).delete()
    except ProtectedError:
        return JsonResponse({"code": 500, "message": "删除失败"})

    return JsonResponse({"code": 200, "message": "删除成功"})


@csrf_exempt
def addSelect(request):
    name = request.POST['name']
    type = request.POST['type']
    select = SelectCollection.objects.create(name=name, type=type)
    select.save()
    if select.id is None:
        return JsonResponse({"code": 500, 'message': '添加失败'})
    return JsonResponse({"code": 200, 'message': '添加成功'})


@csrf_exempt
def updateSelect(request):
    id = request.POST['id']
    name = request.POST['name']
    type = request.POST['type']
    SelectCollection.objects.filter(id=id).update(name=name, type=type)
    return JsonResponse({"code": 200, 'message': '修改成功'})
